package com.rshang.ip;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class IpThread extends Thread{
	private static Log logger = LogFactory.getLog(IpThread.class);
	private final CloseableHttpClient httpClient;
    private final HttpClientContext context;
    private final HttpGet httpget;
	private String ip;
	private String czr;
	private static ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
    
    

	public IpThread(CloseableHttpClient httpClient,
			HttpGet httpget, String ip, String czr) {
		this.httpClient = httpClient;
		this.context = HttpClientContext.create();
		this.httpget = httpget;
		this.ip = ip;
		this.czr = czr;
	}


	@Override
	public void run() {
		IpResult ipData = null;
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(
			        httpget, context);
			int status=response.getStatusLine().getStatusCode();
			
			if(status==200)
			{
				try {
					ipData = mapper.readValue(EntityUtils.toString(response.getEntity()).getBytes("UTF-8"), IpResult.class);
				} catch (Exception e) {
					Db.save("ip_data_err", new Record().set("ip_address",ip).set("lrr",czr));
					e.printStackTrace();
				}finally
				{
					try {
						response.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				Db.save("ip_data", genInsertObject(ipData.getData(),czr));
			}
		} catch (Exception e) {
			Db.save("ip_data_err", new Record().set("ip_address",ip).set("lrr",czr));
			e.printStackTrace();
		}
		//this.logger.info(this.getId()+"end");
	}
	
	private Record genInsertObject(Ip ip,String czr) throws UnsupportedEncodingException
	{
		Record record = new Record();
		record.set("IP_ADDRESS", ip.getIp());
		record.set("country_id", ip.getCountry_id());
		record.set("country_name", ip.getCountry());
		record.set("region_id", ip.getRegion_id());
		record.set("region_name", ip.getCountry());
		record.set("county_id", ip.getCounty_id());
		record.set("county_name", ip.getCounty());
		record.set("city_id", ip.getCity_id());
		record.set("city_name", ip.getCity());
		record.set("area_id", ip.getArea_id());
		record.set("area_name", ip.getArea());
		record.set("isp_id", ip.getIsp_id());
		record.set("isp_name", ip.getIsp());
		 return record;
	}
	
}
